package com.previewlibrary.view;

import com.previewlibrary.GPVideoPlayerAbility;
import com.previewlibrary.GPreviewAbility;
import com.previewlibrary.ResourceTable;
import com.previewlibrary.ZoomMediaLoader;
import com.previewlibrary.enitity.IThumbViewInfo;
import com.previewlibrary.loader.MySimpleTarget;
import com.previewlibrary.loader.VideoClickListener;
import com.previewlibrary.wight.SmoothImageView;

import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;

import uk.co.senab2.photoview2.PhotoViewAttacher;

import java.lang.reflect.Constructor;
import java.util.Locale;
import java.util.Optional;

/**
 * author yangc
 * date 2017/4/26
 * E-Mail:yangchaojiang@outlook.com
 * Deprecated: 图片预览单个图片的fragment
 */
public class BasePhotoFragment extends Fragment {
    /**
     * 预览图片 类型.
     */
    private static final String KEY_TRANS_PHOTO = "is_trans_photo";
    private static final String KEY_SING_FILING = "isSingleFling";
    private static final String KEY_PATH = "key_item";
    private static final String KEY_DRAG = "isDrag";
    private static final String KEY_SEN = "sensitivity";
    private static VideoClickListener listener;
    private IThumbViewInfo beanViewInfo;
    private boolean isTransPhoto = false;
    /**
     * imageView.
     */
    protected SmoothImageView imageView;
    /**
     * rootView.
     */
    protected Component rootView;
    /**
     * loading.
     */
    protected Component loading;
    /**
     * mySimpleTarget.
     */
    protected MySimpleTarget mySimpleTarget;
    /**
     * btnVideo.
     */
    protected Component btnVideo;

    public BasePhotoFragment(Context context) {
        super(context);
    }

    /**
     * setListener .
     *
     * @param listener listener
     */
    public static void setListener(VideoClickListener listener) {
        BasePhotoFragment.listener = listener;
    }

    /**
     * getBasePhotoFragment .
     *
     * @param context       context
     * @param fragmentClass fragmentClass
     * @param item          item
     * @param currentIndex  currentIndex
     * @param isSingleFling isSingleFling
     * @param isDrag        isDrag
     * @param sensitivity   sensitivity
     * @return BasePhotoFragment
     */
    public static BasePhotoFragment getBasePhotoFragment(
            Context context, Class<? extends BasePhotoFragment> fragmentClass,
            IThumbViewInfo item, boolean currentIndex, boolean isSingleFling,
            boolean isDrag, float sensitivity) {
        BasePhotoFragment fragment;
        try {
            Constructor<?> cons = fragmentClass.getConstructor(Context.class);
            fragment = (BasePhotoFragment) cons.newInstance(context);
        } catch (Exception e) {
            fragment = new BasePhotoFragment(context);
        }
        PacMap bundle = new PacMap();
        bundle.putSequenceableObject(BasePhotoFragment.KEY_PATH, item);
        bundle.putBooleanValue(BasePhotoFragment.KEY_TRANS_PHOTO, currentIndex);
        bundle.putBooleanValue(BasePhotoFragment.KEY_SING_FILING, isSingleFling);
        bundle.putBooleanValue(BasePhotoFragment.KEY_DRAG, isDrag);
        bundle.putFloatValue(BasePhotoFragment.KEY_SEN, sensitivity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected Component onCreateView(LayoutScatter layoutScatter, ComponentContainer container) {
        return layoutScatter.parse(ResourceTable.Layout_fragment_image_photo_layout, null, false);
    }

    @Override
    protected void onViewCreate() {
        initView();
        initData();
    }

    @Override
    public void onBackground() {
        ZoomMediaLoader.getInstance().getLoader().onStop(mContext);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        release();
        ZoomMediaLoader.getInstance().getLoader().clearMemory(mContext);
    }

    /**
     * release.
     */
    public void release() {
        isTransPhoto = false;
    }

    /**
     * 初始化控件.
     */
    private void initView() {
        rootView = mRootView;
        loading = findComponentById(ResourceTable.Id_loading);
        imageView = (SmoothImageView) findComponentById(ResourceTable.Id_photoView);
        imageView.setPageSlider(mPageSlider);
        btnVideo = findComponentById(ResourceTable.Id_btnVideo);
        btnVideo.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String video = beanViewInfo.getVideoUrl();
                if (video != null && !video.isEmpty()) {
                    if (listener != null) {
                        listener.onPlayerVideo(video);
                    } else {
                        GPVideoPlayerAbility.startAbility(mContext, video);
                    }
                }
            }
        });
        mySimpleTarget = new MySimpleTarget() {

            @Override
            public void onResourceReady() {
                loading.setVisibility(Component.HIDE);
                String video = beanViewInfo.getVideoUrl();
                if (video != null && !video.isEmpty()) {
                    btnVideo.setVisibility(Component.VISIBLE);
                    AnimatorProperty animatorProperty = btnVideo.createAnimatorProperty();
                    animatorProperty.alphaFrom(0).alpha(1).setDuration(1000).start();
                } else {
                    btnVideo.setVisibility(Component.HIDE);
                }
            }

            @Override
            public void onLoadFailed(Element errorDrawable) {
                loading.setVisibility(Component.HIDE);
                btnVideo.setVisibility(Component.HIDE);
                if (errorDrawable != null) {
                    imageView.setImageElement(errorDrawable);
                }
            }
        };
    }

    private void initArguments() {
        PacMap bundle = getArguments();
        // 非动画进入的Fragment，默认背景为黑色
        if (bundle != null) {
            Optional<Sequenceable> sequenceable = bundle.getSequenceable(KEY_PATH);
            if (sequenceable.isPresent()) {
                beanViewInfo = (IThumbViewInfo) sequenceable.get();
            }
            imageView.setDrag(bundle.getBooleanValue(KEY_DRAG), bundle.getFloatValue(KEY_SEN));
            imageView.setThumbRect(beanViewInfo.getBounds());
            rootView.setTag(beanViewInfo.getUrl());
            isTransPhoto = bundle.getBooleanValue(KEY_TRANS_PHOTO, false);
            if (beanViewInfo.getUrl().toLowerCase(Locale.ROOT).contains(".gif")) {
                imageView.setZoomable(false);
                ZoomMediaLoader.getInstance().getLoader().displayGifImage(mContext, beanViewInfo.getUrl(), imageView, mySimpleTarget);
            } else {
                ZoomMediaLoader.getInstance().getLoader().displayImage(mContext, beanViewInfo.getUrl(), imageView, mySimpleTarget);
            }

        }
        if (!isTransPhoto) {
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setRgbColor(RgbColor.fromArgbInt(0xff000000));
            rootView.setBackground(shapeElement);
        } else {
            imageView.setMinimumScale(0.7f);
        }

    }

    private void initSingleFling() {
        PacMap bundle = getArguments();
        boolean isSingleFling = true;
        // 非动画进入的Fragment，默认背景为黑色
        if (bundle != null) {
            isSingleFling = bundle.getBooleanValue(KEY_SING_FILING);
        }
        if (isSingleFling) {
            imageView.setOnViewTapListener((view, x, y) -> {
                if (imageView.checkMinScale()) {
                    ((GPreviewAbility) mContext).transformOut();
                }
            });
        } else {
            imageView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(Component view, float x, float y) {
                    if (imageView.checkMinScale()) {
                        ((GPreviewAbility) mContext).transformOut();
                    }
                }

                @Override
                public void onOutsidePhotoTap() {
                }
            });
        }
    }


    private void initData() {
        initArguments();
        initSingleFling();
        imageView.setAlphaChangeListener(alpha -> {
            if (alpha == 255) {
                String video = beanViewInfo.getVideoUrl();
                if (video != null && !video.isEmpty()) {
                    btnVideo.setVisibility(Component.VISIBLE);
                } else {
                    btnVideo.setVisibility(Component.HIDE);
                }
            } else {
                btnVideo.setVisibility(Component.HIDE);
            }
            ShapeElement shapeElement = new ShapeElement();
            RgbColor rgbColor = new RgbColor(0, 0, 0, alpha);
            shapeElement.setRgbColor(rgbColor);
            rootView.setBackground(shapeElement);
            if (alpha >= 240) {
                ((GPreviewAbility) mContext).setPreviewRootBg(Color.BLACK.getValue());
            } else {
                ((GPreviewAbility) mContext).setPreviewRootBg(Color.TRANSPARENT.getValue());
            }
        });
        imageView.setTransformOutListener(() -> ((GPreviewAbility) mContext).transformOut());
    }

    /**
     * transformIn.
     */
    public void transformIn() {
        if (imageView != null) {
            imageView.transformIn(new SmoothImageView.OnTransformListener() {
                @Override
                public void onTransformCompleted(SmoothImageView.Status status) {
                    ShapeElement shapeElement = new ShapeElement();
                    shapeElement.setRgbColor(RgbColor.fromArgbInt(0xff000000));
                    rootView.setBackground(shapeElement);
                    //解决闪烁
                    ((GPreviewAbility) mContext).setPreviewRootBg(0xff000000);
                }
            });
        }
    }

    /**
     * transformOut .
     *
     * @param listener listener
     */
    public void transformOut(SmoothImageView.OnTransformListener listener) {
        if (imageView != null) {
            imageView.transformOut(listener);
        }
    }

    /**
     * changeBg .
     *
     * @param color color
     */
    public void changeBg(int color) {
        AnimatorProperty animatorProperty = btnVideo.createAnimatorProperty();
        animatorProperty.alpha(0).setDuration(SmoothImageView.getDuration()).start();
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(color));
        rootView.setBackground(shapeElement);
    }

    /**
     * getBeanViewInfo . IThumbViewInfo
     *
     * @return IThumbViewInfo
     */
    public IThumbViewInfo getBeanViewInfo() {
        return beanViewInfo;
    }
}
